package com.ag.zlw.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.ag.bean.TbLoginRecord;
import com.ag.common.IDUtil;
import com.ag.common.PageUtil;
import com.ag.zlw.dao.TbLoginRecordDAO;

/**
 * 登陆日志
 * 
 * @author 钟龙伟
 * 
 */

@Service("LoginRecordService")
public class LoginRecordService {
	private static final Logger logger = Logger
			.getLogger(LoginRecordService.class);
	@Resource(name = "ZLWTbLoginRecordDAO")
	private TbLoginRecordDAO LoginRecordDAO;

	public PageUtil query(Map<String, String> queryOption) throws Exception {
		StringBuilder countsql = new StringBuilder();
		StringBuilder hsql = new StringBuilder();
		countsql.append("select count(*) from TbLoginRecord l join l.tbUser u join u.tbUserRoles r "
				+ "join r.tbRole ro where l.a = ");
		hsql.append("select l from TbLoginRecord l join fetch l.tbUser u join fetch u.tbUserRoles r "
				+ "join fetch r.tbRole ro where l.a = ");
		countsql.append(IDUtil.PRESERVE);
		hsql.append(IDUtil.PRESERVE);
		List result = null;
		int firstRow = 0;
		int maxRow = 10;
		int page = 1;
		int total = 0;		
		if (!(queryOption == null)) {
			// 获取总数
			logger.info("=====+++====="+spliceHQL(countsql,queryOption).toString());
			total = ((Long)this.LoginRecordDAO.find(
					spliceHQL(countsql, queryOption).toString()).iterator()
					.next()).intValue();
			logger.info("=======+++++++========total=" + total);
			if (queryOption.containsKey("page")
					&& !queryOption.get("page").isEmpty()) {
				page = Integer.parseInt(queryOption.get("page"));
				logger.info("page=" + page);
				firstRow = maxRow * (page - 1);
			}
			if (total != 0) {
			logger.info(spliceHQL(hsql, queryOption).toString());
				result = this.LoginRecordDAO.query(spliceHQL(hsql, queryOption).toString()+" order by l.lrLoginTime desc ", firstRow, maxRow);
				logger.info("===============result=" + result.size());
				logger.info("===============total=" + total);
			}
		} else {
			// 第一次查询,无参数查询										
			total = ((Long) this.LoginRecordDAO.find(countsql.toString()).iterator().next()).intValue();
//			total = this.LoginRecordDAO.find(countsql.toString()).size();
			logger.info("++++++++++++++total====" + total);
			if (total != 0) {
				result = this.LoginRecordDAO.query(hsql.toString()+" order by l.lrLoginTime desc ", firstRow, maxRow);
				logger.info("+++++++++++++++result=" + result.size());
			}
		}
		PageUtil pageUitl = new PageUtil();
		pageUitl.setMaxRow(maxRow);
		pageUitl.setPage(page);
		pageUitl.setTotal(total);
		pageUitl.setList(result);
		return pageUitl;
}


	private StringBuilder spliceHQL(StringBuilder sql,
			Map<String, String> queryOption) {
		if (queryOption.containsKey("UName") // 用户名
				&& !(queryOption.get("UName").isEmpty())) {
			sql.append(" and u.UName = '");
			sql.append(queryOption.get("UName") + "'");
		}
		if (queryOption.containsKey("UId") // 用户登录名
				&& !(queryOption.get("UId").isEmpty())) {
			sql.append(" and u.UId= '");
			sql.append(queryOption.get("UId") + "'");
		}
		if (queryOption.containsKey("RName") // 角色
				&& !"0".equals(queryOption.get("RName"))) {
			sql.append(" and ro.RId = '");
			sql.append(queryOption.get("RName") + "'");
		}
		if (queryOption.containsKey("TimeStart") // 时间段
				&& !queryOption.get("TimeStart").isEmpty()) {
			System.out.println("====TimeStart========"+queryOption.get("TimeStart"));
			sql.append(" and l.lrLoginTime >= ");
			sql.append("'" + queryOption.get("TimeStart")+ "'");
		}
		if (queryOption.containsKey("TimeEnd")
				&& !queryOption.get("TimeEnd").isEmpty()) {
			sql.append(" and l.lrLoginTime <= ");
			System.out.println(queryOption.get("TimeEnd"));
//			sql.append("to_date('" + queryOption.get("TimeEnd")
//					+ "','YYYY-MM-DD hh24:mi:ss') ");
			sql.append("'"+ queryOption.get("TimeEnd")+ "'");
		}
		logger.info("sql = " + sql);
		return sql;
	}

	public void delete(Map<String, String> queryOption) throws Exception {
		StringBuilder hsql = new StringBuilder();
		hsql.append("select l from TbLoginRecord l where l.a = ");
		hsql.append(IDUtil.PRESERVE);
		List<TbLoginRecord> result = null;
		result = LoginRecordDAO.find(spliceHQL(hsql, queryOption).toString());
		LoginRecordDAO.delete(result);
	}
	
	public List<TbLoginRecord> findByTime(String timeStart,String timeEnd) throws Exception{
		String hsql = "select l from TbLoginRecord l join fetch l.tbUser u join fetch u.tbUserRoles r "
		+ "join fetch r.tbRole ro where l.a = "+IDUtil.PRESERVE
		+" and l.lrLoginTime >= "
		+"'" + timeStart + "'"
		+" and l.lrLoginTime <= "
		+"'" + timeEnd+ "'";
		List result = null;
		result = LoginRecordDAO.findByTime(hsql);	
		System.out.println("=========result.size()==========="+result.size());
		return result;
	}
}
